package com.kizuki.io;

import org.junit.Test;

import java.io.*;

public class TestFileIO {

    @Test
    public void testStream() throws IOException{
        File f = new File("d:/java/learnio/TestStream.txt");
        // 准备长度是2的字节数组，用88,89初始化，其对应的字符分别是X,Y
        byte data[] = { 88, 89};

        if (!f.exists()) {
            f.createNewFile();
        }

        FileOutputStream fos = new FileOutputStream(f);
        fos.write(data);
        fos.close();

        FileInputStream fis =new FileInputStream(f);
        //创建字节数组，其长度就是文件的长度
        byte[] all =new byte[(int) f.length()];
        //以字节流的形式读取文件所有内容
        fis.read(all);
        for (byte b : all) {
            //打印出来是65 66
            System.out.println(b);
        }
        String testCode = new String(all, "UTF-8"); // 对于有编码的直接用 -> 字节流转换成字符串
        System.out.println(testCode);
        fis.close();
    }

    @Test
    public void testReadWriter() throws IOException {
        File f = new File("d:/java/learnio/TestReadWriter.txt");

        if (!f.exists()) {
            f.createNewFile();
        }

        try (FileWriter fr = new FileWriter(f)) {
            String data1 ="abcdefg1234567890";
            fr.write(data1.toCharArray());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try (FileReader fr = new FileReader(f)) {
            // 创建字符数组，其长度就是文件的长度
            char[] all2 = new char[(int) f.length()];
            // 以字符流的形式读取文件所有内容
            fr.read(all2);
            for (char b : all2) {
                // 打印出来是A B
                System.out.print(b);
            }
            System.out.println();
            System.out.println(new String(all2));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }



}
